package com.chinawayltd.ews.sample.manager.openApi.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.openapi.OpenApiClient;
import com.chinawayltd.ews.openapi.Request;
import com.chinawayltd.ews.openapi.Response;
import com.chinawayltd.ews.openapi.constant.Constants;
import com.chinawayltd.ews.openapi.constant.HttpHeader;
import com.chinawayltd.ews.openapi.enums.MethodEnum;
import com.chinawayltd.ews.sample.manager.openApi.OpenApiManager;
import com.chinawayltd.ews.sample.manager.openApi.constant.OpenApiConstants;
import com.chinawayltd.ews.sample.model.openApi.DriverDTO;
import com.chinawayltd.ews.sample.model.openApi.OrgDTO;
import com.chinawayltd.ews.sample.model.openApi.TruckDTO;
import com.chinawayltd.ews.sample.model.openApi.UserDTO;
import com.chinawayltd.ews.sample.model.openApi.VehicleHistoryDTO;
import com.chinawayltd.ews.sample.model.openApi.VehicleStatisticsDailyDTO;

/**
 * @program: g7ews4java-sample
 * @description:
 * @author: xiazj
 * @create: 2018-04-17 19:46
 **/
@Service
public class OpenApiManagerImpl extends BaseOpenApiManager implements OpenApiManager {

    private static final int MAX_PAGE_NUMS = 100;

    @Resource(name="openApiClient")
    private OpenApiClient openApiClient;

    public List<TruckDTO> getTrunckAllByOrgCode(String orgcode_like) throws Exception {
        List<TruckDTO> result = new ArrayList<TruckDTO>();
        int currentPageNo = 1;
        int dataLen = 0;
        while (currentPageNo == 1 || dataLen == 100){
            List<TruckDTO> temp = this.getTrunckList(orgcode_like, null, currentPageNo, MAX_PAGE_NUMS, null);
            dataLen = temp.size();
            if(dataLen > 0){
                result.addAll(temp);
            }
            currentPageNo++;
        }
        return result;
    }

    public List<TruckDTO> getTrunckList(String orgcode_like, String carnum_like,
                                        Integer page_no, Integer page_size, String updatetime_ge) throws Exception {
        List<TruckDTO> result = null;
        //请求path
        final String path = "/v1/base/truck/truck_list";

        JSONObject json = new JSONObject();
        if(StringUtils.isNotBlank(orgcode_like)){
            json.put(OpenApiConstants.QUERY_PARAM_ORGCODE_LIKE, orgcode_like);
        }
        if(StringUtils.isNotBlank(carnum_like)){
            json.put(OpenApiConstants.QUERY_PARAM_CARNUM_LIKE, carnum_like);
        }
        if(page_no != null && page_size != null && page_size > 0){
            json.put(OpenApiConstants.QUERY_PARAM_PAGE_NO, page_no);
            json.put(OpenApiConstants.QUERY_PARAM_PAGE_SIZE, page_size);
        }
        if(StringUtils.isNotBlank(updatetime_ge)){
            json.put(OpenApiConstants.QUERY_PARAM_UPDATETIME_GE, updatetime_ge);
        }
        //Body内容
        String body = json.toJSONString();

        Request request = this.getPostRequest(path, body);
        Response response = openApiClient.execute(request);

        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                JSONArray data = responseResult.getJSONArray(OpenApiConstants.RESULT_DATA);
                if(data != null && !data.isEmpty())
                    result = JSON.parseArray(data.toJSONString(), TruckDTO.class);
            }else{
            	throw new RuntimeException("调用查询查询车辆列表接口返回异常"+responseBody);
            }
        }

        return result;
    }
    
    public List<DriverDTO> getDriverList(String updatetime, String orgcode_like) throws Exception {
        List<DriverDTO> result = null;

        //请求path
        final String path = "/v1/base/driver/driver_list";
        JSONObject json = new JSONObject();
        if(StringUtils.isNotBlank(updatetime)){
            json.put(OpenApiConstants.QUERY_PARAM_UPDATETIME, updatetime);
        }
        if(StringUtils.isNotBlank(orgcode_like)){
            json.put(OpenApiConstants.QUERY_PARAM_ORGCODE_LIKE, orgcode_like);
        }

        //Body内容
        String body = json.toJSONString();
        Request request = this.getPostRequest(path, body);
        Response response = openApiClient.execute(request);

        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                JSONArray data = responseResult.getJSONArray(OpenApiConstants.RESULT_DATA);
                if(data != null && !data.isEmpty())
                    result = JSON.parseArray(data.toJSONString(), DriverDTO.class);
            }else{
            	throw new RuntimeException("调用查询司机列表接口返回异常"+responseBody);
            }
        }
        return result;
    }
    
	public VehicleStatisticsDailyDTO getVehicleStatistics(String plateNum, String from, String to) throws Exception {
		VehicleStatisticsDailyDTO result = null;
        // 请求path
        final String path = "/v1/device/truck/fuel";
        // 请求header
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(HttpHeader.HTTP_HEADER_G7_TIMESTAMP, "" + System.currentTimeMillis());
        Request request = new Request(MethodEnum.GET, path, Constants.DEFAULT_TIMEOUT);
        request.setHeaders(headers);
        // 请求的query
        Map<String, String> querys = new HashMap<String,String>();
        querys.put("plate_num", plateNum);

        querys.put("from", from);
        querys.put("to", to);
        request.setQueries(querys);
        
        // 调用服务端
		Response response = openApiClient.execute(request);
		String responseBody = response.getBody();
		if (StringUtils.isNotBlank(responseBody)) {
			JSONObject responseResult = JSON.parseObject(responseBody);
			Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
			Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
			if (code == 0 && subCode == 0) {
				JSONObject data = responseResult.getJSONObject(OpenApiConstants.RESULT_DATA);
				if (data != null && !data.isEmpty())
					result = JSON.parseObject(data.toJSONString(), VehicleStatisticsDailyDTO.class);
			} else {
				throw new RuntimeException("调用查询车辆指定时间段ems总油耗接口返回异常" + responseBody);
			}
		}
		return result;
	}

    public List<OrgDTO> getOrgList(String orgRoot) throws Exception {
        List<OrgDTO> result = null;
        //请求path
        final String path = "/v1/base/org/get_org_by_root";

        JSONObject json = new JSONObject();
        if(StringUtils.isNotBlank(orgRoot)){
            json.put(OpenApiConstants.QUERY_PARAM_ORGROOT, orgRoot);
        }
        json.put(OpenApiConstants.QUERY_PARAM_PAGE_NO, 1);
        json.put(OpenApiConstants.QUERY_PARAM_PAGE_SIZE, MAX_PAGE_NUMS);
        //Body内容
        String body = json.toJSONString();

        Request request = this.getPostRequest(path, body);
        Response response = openApiClient.execute(request);

        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                JSONObject data = responseResult.getJSONObject(OpenApiConstants.RESULT_DATA);
                if(data != null && !data.isEmpty()){
                    result = JSON.parseArray(data.getJSONArray(OpenApiConstants.RESULT_DATA_RESULT).toJSONString(), OrgDTO.class);
                }
            }else{
                throw new RuntimeException("调用查询机构下所有子机构返回异常"+responseBody);
            }
        }

        return result;
    }

    public UserDTO getUserByToken(String token) throws Exception {
        UserDTO result = null;
        //请求path
        final String path = "/v1/base/user/getuserbytoken";

        JSONObject json = new JSONObject();
        if(StringUtils.isBlank(token)){
            throw new RuntimeException("token must be not null!");
        }
        json.put(OpenApiConstants.QUERY_PARAM_USER_TOKEN, token);
        //Body内容
        String body = json.toJSONString();

        Request request = this.getPostRequest(path, body);
        Response response = openApiClient.execute(request);

        String responseBody = response.getBody();
        System.out.println("======token:" + token + ",result:" + responseBody);
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                JSONObject data = responseResult.getJSONObject(OpenApiConstants.RESULT_DATA);
                if (data != null && !data.isEmpty())
                    result = JSON.parseObject(data.toJSONString(), UserDTO.class);
            }
        }

        return result;
    }

	public List<VehicleHistoryDTO> getVehicleHistoryLocation(String plateNum, String from, String to) throws Exception {
		List<VehicleHistoryDTO> result = null;
		if(StringUtils.isBlank(plateNum) || StringUtils.isBlank(from) || StringUtils.isBlank(to)){
			throw new RuntimeException("data must be not null!");
		}
        // 请求path
        final String path = "/v1/device/truck/history_location";
        // 请求header
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(HttpHeader.HTTP_HEADER_G7_TIMESTAMP, "" + System.currentTimeMillis());
        Request request = new Request(MethodEnum.GET, path, Constants.DEFAULT_TIMEOUT);
        request.setHeaders(headers);
        // 请求的query
        Map<String, String> querys = new HashMap<String,String>();
        querys.put("plate_num", plateNum);

        querys.put("from", from);
        querys.put("to", to);
        querys.put("map", "baidu");
        request.setQueries(querys);
        
        // 调用服务端
		Response response = openApiClient.execute(request);
		String responseBody = response.getBody();
		if (StringUtils.isNotBlank(responseBody)) {
			JSONObject responseResult = JSON.parseObject(responseBody);
			Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
			Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
			if(code == 0 && subCode == 0){
                JSONArray data = responseResult.getJSONArray(OpenApiConstants.RESULT_DATA);
                if (data != null && !data.isEmpty())
                	result =JSON.parseArray(data.toString(), VehicleHistoryDTO.class);
            }else{
                throw new RuntimeException("调用查询车辆指定时间段车辆轨迹接口返回异常"+responseBody);
            }
		}
		return result;
	}

	public VehicleHistoryDTO getVehicleCurrentLocation(String plateNum) throws Exception {
		VehicleHistoryDTO result = null;
        // 请求path
        final String path = "/v1/device/truck/current_location";
        // 请求header
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(HttpHeader.HTTP_HEADER_G7_TIMESTAMP, "" + System.currentTimeMillis());
        Request request = new Request(MethodEnum.GET, path, Constants.DEFAULT_TIMEOUT);
        request.setHeaders(headers);
        // 请求的query
        Map<String, String> querys = new HashMap<String,String>();
        querys.put("plate_num", plateNum);
        querys.put("map", "baidu");
        request.setQueries(querys);
        
        // 调用服务端
		Response response = openApiClient.execute(request);
		String responseBody = response.getBody();
		if (StringUtils.isNotBlank(responseBody)) {
			JSONObject responseResult = JSON.parseObject(responseBody);
			Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
			Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
			if(code == 0 && subCode == 0){
				JSONObject data = responseResult.getJSONObject(OpenApiConstants.RESULT_DATA);
				if (data != null && !data.isEmpty())
                    result = JSON.parseObject(data.toJSONString(), VehicleHistoryDTO.class);
            }else{
                throw new RuntimeException("调用查询车辆指定时间段车辆当前位置接口返回异常"+responseBody);
            }
		}
		return result;
	}

}
